<template>
  <div class="app-container">
    <div v-loading="loading" ref="myPage" style="margin-top:50px;width: calc(100% - 10px);height:calc(100vh - 140px);"
         @click="isShowNodeMenuPanel = false">
      <el-button type="success" size="mini" class="c-show-code-button" @click="handleAdd">添加分组</el-button>
      <SeeksRelationGraph ref="seeksRelationGraph" :options="graphOptions" :on-node-expand="onNodeExpand"
                          :on-node-click="onNodeClick" :on-line-click="onLineClick">
        <div slot="node" slot-scope="{node}" class="c-node-text" @click="showNodeMenus(node, $event)"
             @contextmenu.prevent.stop="showNodeMenus(node, $event)">
          {{ node.text }}<br/>
          {{ node.data.duty }}
        </div>
      </SeeksRelationGraph>

    </div>

    <div v-show="isShowNodeMenuPanel"
         :style="{left: nodeMenuPanelPosition.x + 'px', top: nodeMenuPanelPosition.y + 'px' }"
         class="show-node-panel">
      <div style="line-height: 25px;padding-left: 10px;color: #888888;font-size: 12px;">对这个节点进行操作：</div>
      <div class="c-node-menu-item" @click.stop="doAction('1')">修改</div>
      <div class="c-node-menu-item" @click.stop="doAction('2')">删除</div>
    </div>

    <!-- 添加或修改审批流程（审核人）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="审批类目" prop="approveId">
          <el-select v-model="form.approveId" placeholder="审批类目" style="width:100%;" size="mini" clearable>
            <el-option v-for="approve in approveList"
                       :key="approve.id"
                       :label="approve.approveTitle"
                       :value="approve.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="流程模板" prop="templateId">
          <el-select v-model="form.templateId" placeholder="流程模板" style="width:100%;" size="mini" clearable>
            <el-option v-for="template in templateList"
                       :key="template.id"
                       :label="template.templateName"
                       :value="template.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定电话" prop="userNo">
          <el-input v-model="form.phoneNum" placeholder="请输入绑定电话" size="mini"
                    maxlength="30" @change="getListMpSearch">
            <!--            <template slot="append">-->
            <!--              <el-button @click="getListMpSearch" size="mini">搜索</el-button>-->
            <!--            </template>-->
          </el-input>
        </el-form-item>

        <el-form-item label="微信昵称" prop="userId" v-if="wxUserOptions.length > 0">
          <div class="wx-user">
            <el-radio-group v-model="form.userId">
              <el-row v-for="wxUser in wxUserOptions">
                <el-col :span="24">
                  <el-radio :label="wxUser.id" :value="wxUser.id">
                    <a :href="wxUser.faceUrl" style="color: #42b983" target="_blank">
                      <img :src="wxUser.faceUrl" alt="点击打开" class="el-avatar">
                    </a> {{ wxUser.nickName }}({{ wxUser.phoneNum != null ? wxUser.phoneNum : '' }})
                  </el-radio>
                </el-col>
              </el-row>
            </el-radio-group>
          </div>
        </el-form-item>


        <el-form-item label="管理员姓名" prop="sysUserId">
          <el-select v-model="form.sysUserId" ref="nickName" filterable placeholder="管理员"
                     size="mini"
                     style="width:100%;">
            <el-option label="请选择" value=""/>
            <el-option v-for="sysUser in sysUserList"
                       :key="sysUser.userId"
                       :label="sysUser.nickName"
                       :value="sysUser.userId"/>
<!--            <div style="padding: 4px 8px; cursor: pointer">-->
<!--              <el-button type="mini" @click="getListNickName">搜索</el-button>-->
<!--            </div>-->
          </el-select>

        </el-form-item>

        <!--        <el-form-item label="手机号" prop="phoneNum">-->
        <!--          <el-input v-model="form.phoneNum" placeholder="请输入手机号" size="mini"/>-->
        <!--        </el-form-item>-->

        <el-form-item label="所属流程" prop="dutyName">
          <el-select v-model="form.dutyName" ref="nickName" placeholder="所属流程" size="mini"
                     style="width:100%;">
            <el-option label="初审" value="初审"/>
            <el-option label="复审" value="复审"/>
            <el-option label="终审" value="终审"/>
            <el-option label="抄送" value="抄送"/>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state" style="width:95%;" size="mini">
            <el-radio :value="0" :label="0">禁用</el-radio>
            <el-radio :value="1" :label="1">可用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getUser, delUser, addUser, updateUser, exportUser} from "@/api/module/examine/templateUser";
import SeeksRelationGraph from '@/components/RelationGraph';
import {listTemplate, listTemplateNodeList} from "@/api/module/examine/template";
import {listApprove} from "@/api/module/examine/approve";
import {listByPhone} from "@/api/module/wx/user";
import {listUser} from "@/api/system/user";
import {listEstate} from "@/api/module/estate/estate";

export default {
  name: "User",
  components: {
    SeeksRelationGraph,
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批流程（审核人）表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: 2,
      },
      queryParamsWxUser: {
        phoneNum: undefined,
        nickName: undefined,
        platform:"wxwork",
        id: undefined,
      },
      wxUserOptions: [],
      templateList: [],
      approveList: [],
      sysUserList: [],
      queryParamsPty: {
        propertyId: undefined,
      },
      querySysUser: {
        nickName: undefined,
        userId: undefined,
        propertyId: undefined,
        estateId: undefined,
        phoneNum:undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      isShowNodeMenuPanel: false,
      nodeMenuPanelPosition: {},
      graphOptions: {
        'allowSwitchLineShape': true,
        'allowSwitchJunctionPoint': true,
        'backgrounImage': 'http://ai-mark.cn/images/ai-mark-desc.png',
        'backgrounImageNoRepeat': true,
        'layouts': [
          {
            'label': '中心',
            'layoutName': 'tree',
            "centerOffset_x": "0",
            "centerOffset_y": "-100",
            'layoutClassName': 'seeks-layout-center',
            'defaultJunctionPoint': 'border',
            'from': 'left',
            'defaultNodeShape': 0,
            'defaultLineShape': 1,
            'min_per_width': '40',
            'max_per_width': '400',
            'min_per_height': '200',
            // 'max_per_height': '300',
            // distance_coefficient:2 //层级距离
          }
        ],
        'defaultExpandHolderPosition': 'bottom',
        // defaultNodeColor: "rgba(30, 144, 255, 1)",
        'defaultNodeBorderColor': "#90EE90",
        'defaultJunctionPoint': 'lr',
        'defaultLineShape': 1,
        'defaultNodeShape': 1,
        "defaultLineWidth": 2,
        // "allowShowMiniView": true,
        // defaultNodeWidth: 130,
        // defaultNodeHeight: 250,
        // defaultNodeBorderWidth: 0,
        'isMoveByParentNode': false
      },
      templateTree: [],
    }
  },
  created() {
    this.queryParams.id = this.$route.query.templateId ? parseInt(this.$route.query.templateId) : undefined;
    this.querySysUser.propertyId = this.$route.query.propertyId ? this.$route.query.propertyId : undefined;
    // this.querySysUser.estateId = this.$route.query.estateId ? this.$route.query.estateId : undefined;
    this.getList();
    this.getTemplateList();
    this.getApproveList();
  },
  methods: {
    /** 查询审批流程（审核人）列表 */
    getList() {
      this.loading = true;
      listTemplateNodeList(this.queryParams).then(response => {
        this.templateTree = response.data;
        this.setGraphData(this.templateTree);
        this.loading = false;
      });
    },
    selectBlur(e) {
      this.querySysUser.nickName = e.target.value;
    },
    // getListNickName() {
    //   listUser(this.querySysUser).then(response => {
    //     this.sysUserList = response.rows;
    //     console.log(this.sysUserList)
    //   })
    // },
    getListMpSearch() {
      this.queryParamsWxUser.phoneNum = this.form.phoneNum;
      this.querySysUser.phoneNum = this.form.phoneNum;
      listByPhone(this.queryParamsWxUser).then(response => {
        console.log('getListMpSearch', response.data);
        this.wxUserOptions = response.data;
      });
      listUser(this.querySysUser).then(response => {
        this.sysUserList = response.rows;
        console.log(this.sysUserList)
      })
    },

    getTemplateList() {
      this.queryParamsPty.propertyId = this.form.propertyId;
      listTemplate(this.queryParamsPty).then(response => {
        this.templateList = response.rows;
      });
    },
    getApproveList() {
      this.queryParamsPty.propertyId = this.form.propertyId;
      listApprove(this.queryParamsPty).then(response => {
        this.approveList = response.rows;
      });
    },
    setGraphData(jsonTree) {
      var that = this;
      var __graph_json_data = jsonTree;
      that.g_loading = true;
      console.log('__graph_json_data', JSON.stringify(__graph_json_data));
      setTimeout(function () {
        that.g_loading = false;
        that.$refs.seeksRelationGraph.setJsonData(__graph_json_data, (seeksRGGraph) => {
          // 这些写上当图谱初始化完成后需要执行的代码
        })
      }.bind(this), 1500);
    },
    doAction(actionName) {
      if (actionName == '1') {
        if (this.currentNode.data) {
          let data = this.currentNode.data;
          this.form.id = data.tid;
          this.form.groupName = this.currentNode.text;
          this.form.duty = data.duty;
          console.log(this.form.id)
          console.log(data.tid)
          this.handleUpdate(this.form.id);
        }
        this.title = "修改";
      } else if (actionName == '2') {
        if (this.currentNode.data) {
          let data = this.currentNode.data;
          this.handleDelete(data.tid);
        }
      }
    },
    onNodeClick(nodeObject, $event) {
      console.log('onNodeClick:', nodeObject);
      this.showNodeMenus(nodeObject, $event);
    },
    onNodeExpand(node, e) {
      var that = this;
      //模拟动态加载数据
      if (node.data && node.data.asyncChild === true && node.data.loaded === false) {
        this.loading = true;
        node.data.loaded = true;
        setTimeout(function () {
          this.loading = false;
          var _new_json_data = {
            nodes: [
              {id: node.id + '-child-1', text: node.id + '-的子节点1'},
              {id: node.id + '-child-2', text: node.id + '-的子节点2'},
              {id: node.id + '-child-3', text: node.id + '-的子节点3'}
            ],
            links: [
              {from: node.id, to: node.id + '-child-1', text: '动态子节点'},
              {from: node.id, to: node.id + '-child-2', text: '动态子节点'},
              {from: node.id, to: node.id + '-child-3', text: '动态子节点'}
            ]
          };
          that.$refs.seeksRelationGraph.appendJsonData(_new_json_data, (seeksRGGraph) => {
            // 这些写上当图谱初始化完成后需要执行的代码
          })
        }.bind(this), 1000);

      }
    },
    /** 显示右键菜单 */
    showNodeMenus(nodeObject, $event) {
      this.currentNode = nodeObject;
      console.log('nodeObject', nodeObject);
      var _base_position = this.$refs.myPage.getBoundingClientRect();
      console.log('showNodeMenus:$event,', $event);
      console.log('showNodeMenus: _base_position', _base_position);
      this.isShowNodeMenuPanel = true;
      this.nodeMenuPanelPosition.x = $event.clientX - _base_position.x;
      this.nodeMenuPanelPosition.y = $event.clientY - _base_position.y;
    },
    onLineClick(lineObject, $event) {
      console.log('onLineClick:', lineObject)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        approveId: undefined,
        templateId: undefined,
        sysUserId: undefined,
        userId: undefined,
        openId: undefined,
        unionId: undefined,
        phoneNum: undefined,
        dutyName: undefined,
        dutyIndex: undefined,
        sort: undefined,
        state: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加审批流程（审核人）";
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.loading = true;
      this.reset();
      getUser(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.queryParamsWxUser.id = this.form.userId;
        this.querySysUser.userId = this.form.sysUserId;
        this.open = true;
        this.getListMpSearch();
        this.title = "修改审批流程（审核人）";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(id) {
      const ids = id
      this.$confirm('是否确认删除审批流程（审核人）编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delUser(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有审批流程（审核人）数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportUser(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.tactics-chart-view {
  width: 100%;
  position: relative;
  overflow: hidden;

  .c-show-code-button {
    position: absolute;
    top: 80px;
    right: 30px;
  }
}

.show-node-panel {
  z-index: 999;
  padding: 10px;
  background-color: #ffffff;
  border: #eeeeee solid 1px;
  box-shadow: 0px 0px 8px #cccccc;
  position: absolute;
}

.c-node-menu-item {
  cursor: pointer;
}
</style>

